package ee.ttu.lecture;

import java.util.Iterator;
import java.util.List;

import com.google.appengine.api.datastore.QueryResultIterable;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.NotFoundException;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

import ee.ttu.lecture.data.Lecture;
import ee.ttu.lecture.data.Rating;
import ee.ttu.lecture.data.User;

public class DataAccess
{
	private static boolean init = false;
	private static DataAccess access;
	
	public static DataAccess getDataAccess()
	{
		if(access == null) access = new DataAccess();
		return access;
	}
	
	private DataAccess(){}
	
	static
	{
		if(!init)
		{
			ObjectifyService.register(Lecture.class);
			ObjectifyService.register(Rating.class);
			ObjectifyService.register(User.class);
			
			init = true;
		}
	}
	
	public void storeLecture(Lecture lecture)
	{
		Objectify ofy = ObjectifyService.begin();
		ofy.put(lecture);
	}
	
	public List<Lecture> getLectures()
	{
		Objectify ofy = ObjectifyService.begin();
		Query<Lecture> q = ofy.query(Lecture.class);
		return q.list();
	}
	
	public Lecture getLecture(long id)
	{
		Objectify ofy = ObjectifyService.begin();
		try {
			return ofy.get(Lecture.class, id);
		}
		catch(NotFoundException ex) {
			return null;
		}
	}
	
	public void storeUser(User user)
	{
		Objectify ofy = ObjectifyService.begin();
		ofy.put(user);
	}
	
	public List<User> getUsers()
	{
		Objectify ofy = ObjectifyService.begin();
		Query<User> q = ofy.query(User.class);
		return q.list();
	}
	
	public User getUserByName(String name)
	{
		User user = null;
		Objectify ofy = ObjectifyService.begin();
		QueryResultIterable<User> query_result = ofy.query(User.class).filter("username", name).fetch();
		Iterator<User> iter = query_result.iterator();
		
		int result_count = 0;
		while(iter.hasNext())
		{
			if(result_count != 0)
			{
				user = null;
				//set warning
				break;
			}
			else user = iter.next();
			result_count ++;
		}
		
		return user;
	}
	
	public long storeRating(Rating rating)
	{
		Objectify ofy = ObjectifyService.begin();
		return ofy.put(rating).getId();
	}
	
	public List<Rating> getRating(long lectureId)
	{
		Objectify ofy = ObjectifyService.begin();
		Key<Lecture> lectureKey = new Key<Lecture>(Lecture.class, lectureId);
		return ofy.query(Rating.class).filter("lecture", lectureKey).list();
	}
}
